import React from 'react';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import {
    Card, Button, Row, Col, Select, DatePicker, Input, Checkbox,
    Form, Tabs, message, InputNumber, Table, Modal, Switch, Upload, Collapse, Space
} from 'antd';
import {
    PlusOutlined,
    ImportOutlined,
    PrinterOutlined,
    LoadingOutlined
} from '@ant-design/icons';
import { connect } from 'umi';
import VendorQuick from '../purchase/vendorQuick';
import moment from 'moment';
import * as Request from '@/services/Request';
import PartQuick from './partQuick';
import UploadUtil from '@/components/UploadUtil';
import ImgQuick from '@/pages/admin/imgQuick';
import CateComp from '@/components/CategoryComponent';
import { EmpSelect } from '@/components/FormItemSelect';

const { TabPane } = Tabs;
const apiURL = "/api/services/app/Part/";
class ViewPage extends React.Component<any, any> {
    constructor(props: any) {
        super(props);
        this.state = {
            loading: false,
            loading2: false,
            visible: false,
            visible2: false,
            visible3: false,
            activeKey: '2',
            layout: 'Content',
            record: {
                part: {},
                partRev: {}
            },
            dataSource: [],
            optionPartRev: [],
            fileList: []
        }
    }
    formRef: any = React.createRef();
    componentDidMount() {
        this.fetchDatas();
        this.fetchCate();
    }
    onFinish = (values: any) => {
        var part = values.part;
        var partRev = values.partRev;
        this.partEdit(part, partRev);
    }
    partEdit = (part: any, partRev: any) => {
        part.pum = part.salesUM = part.ium;
        part.warrantyDate = part.warrantyDate?.format('YYYY-MM-DD');
        this.setState({ loading: true });

        var act = "Modify";
        if (part.id == 0 || !part.id) {
            act = "New";
        }
        if (this.state.fileList) {
            var pics: string[] = [];
            this.state.fileList.forEach((element: any) => {
                pics.push(element.response.result);
            });
            part.ImageFileName = pics.toString();
        }
        else {
            part.ImageFileName = this.state.datas.ImageFileName
        }
        Request.post(apiURL + act, part).then((response) => {
            if (response) {
                if (response.success) {
                    if (response.result.success) {
                        message.success('保存成功！');
                        this.partRevEdit(part, partRev);
                        this.fetchDatas();
                    }
                    else {
                        message.error(response.result.message);
                    }
                }
                else {
                    message.error(response.error.message);
                }
                this.setState({ loading: false });
            }
        });

    }
    partRevEdit = (part: any, partRev: any) => {
        if (part && partRev) {
            partRev.partNum = part.partNum;
            partRev.revisionNum = partRev.revShortDesc;
            partRev.effictivDate = partRev.effictivDate?.format('YYYY-MM-DD');
            var act = "Abp/update";
            if (partRev.id == 0 || !partRev.id) {
                act = "Abp/create";
            }
            this.props.dispatch({
                type: act,
                payload: partRev,
                control: 'PartRev',
            }).then(() => {
                var resp = this.props.response;
                if (resp.success) {
                    if (!resp.result) {
                        message.warning('物料版本号有重复！');
                    }
                }
                else {
                    message.error('物料版本保存错误，请联系管理员！');
                }
            });
        }
    }
    fetchDatas = () => {
        this.setState({ loading: true });
        this.props.dispatch({
            type: "Abp/getAll",
            payload: { SkipCount: 0, MaxResultCount: 100 },
            control: 'Part',
        }).then(() => {
            var resp = this.props.response.result?.items;
            this.setState({
                dataSource: resp,
                loading: false,
            });
        });
    }
    setCurrent = (part?: any, partRev?: any) => {
        this.setState({ activeKey: '1', record: { part, partRev } });
        if (part) {
            if (part.warrantyDate)
                part.warrantyDate = moment(part.warrantyDate);
            var fileList: any = [];
            if (part.imageFileName) {

                var pics = part.imageFileName.split(',');
                pics.forEach((element: any) => {
                    var obj = {
                        uid: element,
                        name: element,
                        response: {
                            result: element
                        },
                        status: 'done',
                        url: UploadUtil.imgServ + element,
                    }
                    fileList.push(obj);
                });                
            }
            this.setState({ fileList });
            this.formRef.current.setFieldsValue({ part });
            this.fetchRevs(part.partNum);
        }
        setTimeout(() => {
            this.setState({ visible3: false });
        }, 500);
    }
    createNewPart = () => {
        this.formRef.current.setFieldsValue({ part: null });
        this.formRef.current.setFieldsValue({ partRev: null });
    }
    openModal = (record: any, layout: string) => {
        this.setState({ visible: true, disabled: true, record, layout });
    }
    openModal2 = () => {
        this.setState({ visible2: true });
    }
    openModal3 = () => {
        this.setState({ visible3: true });
    }
    closeModal = () => {
        this.setState({ visible: false });
    }
    closeModal2 = () => {
        this.setState({ visible2: false });
    }
    closeModal3 = () => {
        this.setState({ visible3: false });
    }
    fetchCate = () => {
        this.props.dispatch({
            type: 'Abp/getTreeList',
            payload: { layout: 'Part-ProdCode' },
            control: 'Category'
        }).then(() => {
            this.setState({ optionProdCode: this.props.response.result });
        })
        this.props.dispatch({
            type: 'Abp/getTreeList',
            payload: { layout: 'Part-ClassID' },
            control: 'Category'
        }).then(() => {
            this.setState({ optionClassID: this.props.response.result });
        })
    }
    fetchRevs = (partNum: string) => {
        this.props.dispatch({
            type: 'Abp/getAllByPart',
            payload: { partNum },
            control: 'PartRev'
        }).then(() => {
            var items = this.props.response.result
            this.setState({ optionPartRev: items });
            let partRev = items[0];
            if (partRev) {
                if (partRev.effectiveDate)
                    partRev.effectiveDate = moment(partRev.effectiveDate);
                if (partRev.approvedDate)
                    partRev.approvedDate = moment(partRev.approvedDate);
            }
            this.formRef.current.setFieldsValue({ partRev });
        })
    }
    createNewRev = () => {
        this.formRef.current.setFieldsValue({ partRev: null });
    }
    handleRevChange = (value: any) => {
        const { optionPartRev } = this.state;
        let partRev = optionPartRev.filter((item: any) => item.revisionNum == value)[0];
        if (partRev) {
            if (partRev.effectiveDate)
                partRev.effectiveDate = moment(partRev.effectiveDate);
            if (partRev.approvedDate)
                partRev.approvedDate = moment(partRev.approvedDate);
        }
        this.formRef.current.setFieldsValue({ partRev });
    };
    handleUploadList = (info: any) => {
        this.setState({ fileList: info.fileList });
    }
    clickMultiFun = (val: string[]) => {
        let fileList = this.state.fileList;
        val.forEach((element: any) => {
            var obj = {
                uid: element,
                name: element,
                response: {
                    result: element
                },
                status: 'done',
                url: UploadUtil.imgServ + element,
            }
            fileList.push(obj);
        });
        this.setState({ fileList, visible4: false });
    }
    render() {
        const { record, loading, fileList } = this.state;
        const layout = {
            labelCol: { span: 5 },
            wrapperCol: { span: 19 },
        };
        const optionPartRev = this.state.optionPartRev?.map((d: any) => { return (<Select.Option value={d.revisionNum} key={d.id}>{d.revisionNum}</Select.Option>) });
        const uploadButton = (
            <div>
                {loading ? <LoadingOutlined /> : <PlusOutlined />}
                <div className="ant-upload-text">上传图片</div>
            </div>
        );
        return (
            <PageHeaderWrapper title={false}>
                <Form {...layout} ref={this.formRef} onFinish={this.onFinish} >
                    <Space>
                        <Button type="primary" icon={<PlusOutlined />} onClick={this.createNewPart}>新增</Button>
                        <Button type="primary" htmlType="submit">保存</Button>
                        <Button icon={<ImportOutlined />}>导入</Button>
                        <Button icon={<PrinterOutlined />}>打印预览</Button>
                    </Space>
                    <Card style={{ marginTop: 8 }}>
                        <Tabs defaultActiveKey="1" >
                            <TabPane tab="明细" key="1">
                                <Row gutter={[16, 16]}>
                                    <Col span={15}>
                                        <Form.Item name={['part', 'id']} style={{ display: 'none' }}>
                                            <Input />
                                        </Form.Item>
                                        <Form.Item label="物料编码" style={{ marginBottom: 0 }}>
                                            <Input.Group compact>
                                                <Form.Item name={['part', 'partNum']}
                                                    rules={[{ required: true, message: "物料编码必填" }]}>
                                                    <Input style={{ width: 138 }} />
                                                </Form.Item>
                                                <CateComp layout="IUM" width={100} name={['part', 'ium']} required={true} />
                                                <Form.Item name={['part', 'searchWord']}
                                                    rules={[{ required: true, message: "搜索关键词必填" }]}>
                                                    <Input placeholder="搜索关键词" style={{ width: 100 }} />
                                                </Form.Item>
                                                <Form.Item>
                                                    <Button type="primary" onClick={this.openModal3}>选择</Button>
                                                </Form.Item>
                                            </Input.Group>
                                        </Form.Item>

                                        <Form.Item name={['part', 'partDescription']} label="物料描述"
                                            rules={[{ required: true }]}>
                                            <Input />
                                        </Form.Item>
                                        <Form.Item name={['part', 'costMethod']} label="成本方法"
                                            rules={[{ required: true }]}>
                                            <Select style={{ width: 200 }} placeholder="核算方法">
                                                <Select.Option key="Average" value="A">平均</Select.Option>
                                                <Select.Option key="First" value="F">先进先出</Select.Option>
                                                <Select.Option key="Last" value="L">最后</Select.Option>
                                                <Select.Option key="Standard" value="S">标准</Select.Option>
                                            </Select>
                                        </Form.Item>
                                        <Form.Item name={['part', 'typeCode']} label="类型">
                                            <Select style={{ width: 200 }} placeholder="请选择类型">
                                                <Select.Option value="M">制造</Select.Option>
                                                <Select.Option value="P">外购</Select.Option>
                                            </Select>
                                        </Form.Item>
                                        <CateComp layout="Part-ClassID" width={200} name={['part', 'classID']} label="分类" />
                                        <CateComp layout="Part-ProdCode" width={200} name={['part', 'prodCode']} label="群组" />
                                        <Form.Item
                                            name={['part', 'warrantyDate']}
                                            label="保修期">
                                            <DatePicker />
                                        </Form.Item>
                                    </Col>
                                    <Col span={9}>
                                        <Form.Item>
                                            <Input.Group compact>
                                                <Form.Item name={['part', 'inActive']} valuePropName="checked">
                                                    <Checkbox>禁用</Checkbox>
                                                </Form.Item>
                                                <Form.Item name={['part', 'globalLock']} valuePropName="checked">
                                                    <Checkbox>全局锁定</Checkbox>
                                                </Form.Item>
                                                <Form.Item name={['part', 'trackLots']} valuePropName="checked">
                                                    <Checkbox>批次追踪</Checkbox>
                                                </Form.Item>
                                                <Form.Item name={['part', 'webPart']} valuePropName="checked">
                                                    <Checkbox>电商产品</Checkbox>
                                                </Form.Item>
                                                <Form.Item name={['part', 'dropShip']} valuePropName="checked">
                                                    <Checkbox>直接出货</Checkbox>
                                                </Form.Item>
                                                <Form.Item name={['part', 'nonStock']} valuePropName="checked">
                                                    <Checkbox>非库存项目</Checkbox>
                                                </Form.Item>
                                                <Form.Item name={['part', 'buyToOrder']} valuePropName="checked">
                                                    <Checkbox>订单式购买</Checkbox>
                                                </Form.Item>
                                                <Form.Item name={['part', 'purSuggest']} valuePropName="checked">
                                                    <Checkbox>生成采购建议</Checkbox>
                                                </Form.Item>
                                            </Input.Group>
                                        </Form.Item>
                                        <Form.Item>
                                            <Upload
                                                action={UploadUtil.uploadURL}
                                                headers={{
                                                    'Authorization': UploadUtil.accessToken,
                                                }}
                                                data={{
                                                    objectId: record?.part?.id,
                                                    objectName: 'Part',
                                                    objectField: 'ImageFileName'
                                                }}
                                                listType="picture-card"
                                                fileList={fileList}
                                                multiple={true}
                                                onChange={this.handleUploadList}>
                                                {fileList.length >= 6 ? null : uploadButton}
                                            </Upload>
                                            <Button onClick={() => this.setState({ visible4: true })} >选择图片</Button>
                                        </Form.Item>
                                    </Col>
                                </Row>
                            </TabPane>
                            <TabPane tab="MRP属性" key="2">
                                <Form.Item name={['part', 'maxnum']} label="最大库存量">
                                    <InputNumber />
                                </Form.Item>
                                <Form.Item name={['part', 'minnum']} label="最小库存量">
                                    <InputNumber />
                                </Form.Item>
                                <Form.Item name={['part', 'saftQty']} label="安全库存">
                                    <InputNumber />
                                </Form.Item>
                                <EmpSelect required={true} width={200} name={['part', 'buyerID']} label="默认采购员" />
                                <Form.Item name={['part', 'minBuyQty']} label="最少起订量">
                                    <InputNumber />
                                </Form.Item>
                                <Form.Item name={['part', 'preDay']} label="前置时间">
                                    <Input suffix="天" style={{ width: 200 }} />
                                </Form.Item>
                                <Form.Item label="默认供应商">
                                    <Input.Group compact>
                                        <Form.Item name={['part', 'vendorID']}>
                                            <Select style={{ width: 200 }} placeholder="请选择默认供应商">
                                            </Select>
                                        </Form.Item>
                                        <Form.Item><Button icon={<PlusOutlined />} onClick={this.openModal2} /></Form.Item>
                                    </Input.Group>
                                </Form.Item>

                            </TabPane>
                            <TabPane tab="版本" key="3">
                                <Form.Item label="版本号" style={{ marginBottom: 0 }}>
                                    <Input.Group compact>
                                        <Form.Item name={['partRev', 'revisionNum']}>
                                            <Select
                                                style={{ width: 150 }}
                                                placeholder="请选择版本"
                                                showSearch
                                                onChange={this.handleRevChange}
                                            >
                                                {optionPartRev}
                                            </Select>
                                        </Form.Item>
                                        <Form.Item name={['partRev', 'revShortDesc']}>
                                            <Input placeholder="版本缩写" />
                                        </Form.Item>
                                    </Input.Group>
                                </Form.Item>
                                <Form.Item name={['partRev', 'revDescription']} label="版本描述">
                                    <Input />
                                </Form.Item>

                                <Form.Item
                                    name={['partRev', 'effectiveDate']}
                                    label="生效日期"
                                    rules={[{ required: true, message: "请选择生效日期" }]}>
                                    <DatePicker />
                                </Form.Item>
                                <Form.Item name={['partRev', 'approved']} label="核准" valuePropName="checked">
                                    <Checkbox />
                                </Form.Item>
                                <Form.Item name={['partRev', 'approvedDate']} label="核准日期">
                                    <DatePicker disabled={true} />
                                </Form.Item>
                                <Form.Item name={['partRev', 'id']} label="ID" style={{ display: 'none' }}>
                                    <Input />
                                </Form.Item>
                                <Form.Item wrapperCol={{ offset: 5 }}>
                                    <Button block type="dashed" icon={<PlusOutlined />} onClick={this.createNewRev}>新增版本</Button>
                                </Form.Item>
                            </TabPane>
                            <TabPane tab="替代" key="4">
                                <Form.Item name={['part', 'xPartNum']} label="替代物料">
                                    <Input style={{ width: 200 }} />
                                </Form.Item>
                                <Form.Item name={['part', 'xPartDescription']} label="物料描述">
                                    <Input.TextArea disabled />
                                </Form.Item>
                            </TabPane>
                            <TabPane tab="其它属性" key="5">
                                <Form.Item label="尺寸" style={{ marginBottom: 0 }}>
                                    <Input.Group compact>
                                        <Form.Item name={['part', 'partLength']}>
                                            <InputNumber step={0.1} placeholder="长" />
                                        </Form.Item>
                                        <Form.Item name={['part', 'partWidth']}>
                                            <InputNumber step={0.1} placeholder="宽" />
                                        </Form.Item>
                                        <Form.Item name={['part', 'partHeight']}>
                                            <InputNumber step={0.1} placeholder="高" />
                                        </Form.Item>
                                    </Input.Group>
                                </Form.Item>
                                <Form.Item name={['part', 'diameter']} label="直径">
                                    <InputNumber step={0.1} />
                                </Form.Item>
                                <Form.Item name={['part', 'gravity']} label="重力">
                                    <InputNumber step={0.1} />
                                </Form.Item>
                                <Form.Item name={['part', 'netVolume']} label="净容量">
                                    <InputNumber step={0.1} />
                                </Form.Item>
                                <Form.Item name={['part', 'grossWeight']} label="毛重">
                                    <InputNumber step={0.1} />
                                </Form.Item>
                                <Form.Item name={['part', 'netWeight']} label="净重">
                                    <InputNumber step={0.1} />
                                </Form.Item>
                            </TabPane>
                        </Tabs>
                    </Card>
                </Form>
                <Modal
                    title="供应商编辑"
                    width={1000}
                    visible={this.state.visible2}
                    destroyOnClose={true}
                    onCancel={this.closeModal2}
                    footer={false}
                >
                    <VendorQuick />
                </Modal>
                <Modal
                    title="物料选择"
                    visible={this.state.visible3}
                    destroyOnClose={true}
                    onCancel={this.closeModal3}
                    footer={false}
                >
                    <PartQuick setPart={(item: any) => this.setCurrent(item)} />
                </Modal>
                <Modal
                    title='图片选择'
                    visible={this.state.visible4}
                    destroyOnClose={true}
                    onCancel={() => this.setState({ visible4: false })}
                    width={750}
                    footer={false}
                >
                    <ImgQuick clickMultiFun={(val: any) => this.clickMultiFun(val)} />
                </Modal>
            </PageHeaderWrapper>
        )
    }
}
export default connect(({ Abp }: API.IConnectState) => ({
    response: Abp.response,
    currentUser: Abp.currentUser,
}))(ViewPage);